import React, { Component } from 'react';
import PropTypes from 'prop-types';
import * as echarts from 'echarts';
// 基础图表
import 'echarts/lib/chart/line';
import 'echarts/lib/chart/bar';
import 'echarts/lib/chart/pie';
import 'echarts/lib/chart/radar';
import 'echarts/lib/chart/tree';
import 'echarts/lib/chart/treemap';
import 'echarts/lib/chart/effectScatter';
import 'echarts/lib/chart/custom';
// 组件
import 'echarts/lib/component/tooltip';
import 'echarts/lib/component/title';
import 'echarts/lib/component/dataZoom';
import 'echarts/lib/component/legend';
import 'echarts/lib/component/geo';
import 'echarts/lib/component/visualMap';

import './index.less';

class MyECharts extends Component {
  constructor(props) {
    super(props);
    this.wrapper = React.createRef();
    this.myChart = null;
    this.onResize = null;
  }

  componentDidMount() {
    this.setOption();
  }

  componentDidUpdate() {
    this.setOption();
  }

  setOption() {
    if (!this.myChart && this.wrapper && this.wrapper.current) {
      this.myChart = echarts.init(this.wrapper.current);
      this.myChart.on('click', this.props.onClick);
      let events = this.props.events || {};
      for (let eventName of Object.keys(events)) {
        if (typeof events[eventName] === 'function') {
          this.myChart.on(eventName, (...params) => events[eventName](...params, this.myChart));
        }
      }
      this.onResize = this.myChart.resize;
      window.addEventListener('resize', this.onResize);
    }
    if (this.myChart) {
      this.myChart.setOption(this.props.option);
      setTimeout(this.onResize);
    }
  }

  // TODO 图表点击事件提取到配置项
  // bindEvent() {
  //   const { series } = this.option;
  //   const chart = this.myChart;
  //   if (!chart) {
  //     return;
  //   }
  //   const seriesArray = Array.isArray(series) ? series : [series];
  //   seriesArray.forEach((serie, seriesIndex) => {
  //     const { data, onClick } = serie;
  //     if (typeof onClick === 'function') {
  //       chart.on('click', { seriesIndex }, onClick.bind(this, serie, seriesIndex));
  //     }
  //     data.forEach((item, dataIndex) => {
  //       chart.on(
  //         'click',
  //         { seriesIndex, dataIndex },
  //         onClick.bind(this, item, dataIndex, seriesIndex)
  //       );
  //     });
  //   });
  // }

  componentWillUnmount() {
    if (this.myChart && this.myChart.dispose) {
      this.myChart.dispose();
    }
    window.removeEventListener('resize', this.onResize);
  }

  render() {
    return <div className="my-echart" ref={this.wrapper} />;
  }
}

MyECharts.propTypes = {
  option: PropTypes.object,
  onClick: PropTypes.func,
  events: PropTypes.object
};

export default MyECharts;
